import React, {Component} from 'react';
import {connect} from 'dva';
import {
  Form, Input, Button, Upload, Select, Icon, DatePicker, message, Modal
} from 'antd';
import moment from 'moment';
// import styles from './Company.less';
import * as ajax from "../../../services/api";
// import { isAbsolute } from 'path';
import bcx_utils from "../../../common/bcx_utils";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const {Option} = Select;
const {confirm} = Modal;

@connect(state => ({
  global: state.global
}))

@Form.create()

/**
 * 企业保险，线下，编辑页面
 */
export default class InsuranceDetails extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // comInsId: this.props.match.params.comInsId,//传过来的方案id
      comInsId: this.props.comInsId,//传过来的方案id
      loading:false,
      guaProjectOptions:[],
      listPage: {
        comName: this.props.global.companyInfo.comName,//公司名称
        productName:'',//保险产品名称
        perNum:'',//在保人数
        effectStartDate:'',//保险有效期开始时间
        effectEndDate:'',//保险有效期结束时间
        insComName:'',//保险公司名称
        policyNo:'',//保单号
      },
      mode:['date', 'date'],
      comInsGuaProject:[
        {
          seq:1,
          guaranteeProject:'',
          guaranteeAmount:'',
        }
      ],//保障信息内容
      // fileList: [],
      fileList: [],
      proLength:1,//有多少个保障项目
    };
    console.log(this,"XXXXXXXXXXXXXXXXXXXXXXXXX");
  }

  componentDidMount() {
    //下拉保障项目data
    ajax.getInsProjects().then((data) => {
      // console.log('下拉保障项目data:', data);
      this.setState({ guaProjectOptions: data.data});
    });
    this.messageList();
  }

  //查询详情
  messageList = () => {
    if(this.state.comInsId !== '00'){
      ajax.comInsGetComInsDetail({comInsId: this.state.comInsId}).then((data) => {
        console.log('企业保险详情',data.data);
        //构造多个fileList
        let fileListDetail = [];
        if(data.data.comIns.policyUrl !== ""){
          fileListDetail = data.data.comIns.policyUrl.split(",").map((val,key) => {
            const str = val.split("/");
            return {
              uid: key,
              name: str[str.length - 1] ,
              status: 'done',
              response:{
                data: val
              },
              url: val,
            };
          });
        }
        this.setState({
          listPage:data.data.comIns,
          comInsGuaProject:data.data.comInsGuaProjectList,
          proLength:data.data.comInsGuaProjectList.length === 0 ? 1 : data.data.comInsGuaProjectList.length,
          fileList:fileListDetail
        });
        console.log('232232323',data.data.comIns.policyUrl);
      },(err) => {
        console.log(err);
      });
    }
  };


  // handleCancel = () => {
  //   this.setState({previewVisible: false});
  // }

  // handlePreview = (file) => {
  //   this.setState({
  //     previewImage: file.url || file.thumbUrl,
  //     previewVisible: true,
  //   });
  // };

  //保存事件
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, value) => {
      const values = value;
      console.log('保单: ', values.policyUrl);
      if (!err) {
        console.log('validateFields: ', values);
        const rangeValue = values['rangeTimePicker'];
        values.effectStartDate = rangeValue[0].format('YYYY-MM-DD');
        values.effectEndDate = rangeValue[1].format('YYYY-MM-DD');
        values.comInsGuaProjectList = [];
        for(let i = 1; i <= this.state.proLength; i++){
          values.comInsGuaProjectList.push({
            seq: i,
            guaranteeProject:values[`guaranteeProject${i}`],
            guaranteeAmount:values[`guaranteeAmount${i}`],
          });
          delete values[`guaranteeProject${i}`];
          delete values[`guaranteeAmount${i}`];
        }
        //如果没有上传附件，那么就不上传这个policyUrl的变量
        let url = "";
        if(values.policyUrl.file){
          // values.policyUrl = values.policyUrl.file.response.data;
            //设置url
            console.log(">>>xxxxx>>>>>>>>>>>>>>>", values.policyUrl);
          values.policyUrl.fileList.map((val) => {
            if(val.response){
              url += val.response.data + ",";
            }
            return 1;
          });
          url = url.substring(0, url.length - 1);
          values.policyUrl = url;
        }else{
          delete values.policyUrl;
        }
        values.comInsId = this.state.comInsId;
        values.buyMode = '2';
        values.comInsGuaProjectList = JSON.stringify(values.comInsGuaProjectList);
        delete values.rangeTimePicker;
        console.log('comInsGuaProjectList',values.comInsGuaProjectList);
        console.log('values',values);
        //区分是新增，还是修改
        this.setState({ loading: true });
        if(this.state.comInsId === '00'){ //新增
          delete values.comInsId;
          ajax.comInsInsertComInsUnderline({...values}).then(() => {
            // message.success('提交成功!');
            this.setState({ loading: false });
            this.props.close();
          },(error) => {
            message.warning('新增企业保险err',error);
          });
        }else{ //修改
          ajax.comInsInsertComInsUnderline({...values}).then(() => {
            // message.success('提交成功!');
            this.setState({ loading: false });
            this.props.close();
          },(error) => {
            message.warning('新增企业保险err',error);
          });
        }
      }
    });
  };

  callback = (key) => {
    console.log(key);
  };

  //校验金额
  checkJinE = (rule, value, callback) => {
    if(value === ' '){
      callback('保障项目金额不能为空！');
    }else if (value && !(/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/).test(value)) {
      callback('保障项目金额输入不正确！');
    }else {
      callback();
    }
  };

  //增加保障项目
  addArea = ()=> {
    const protectionList = this.state.comInsGuaProject;
    const proVal = this.state.comInsGuaProject.length + 1;
    console.log('前：' + protectionList);
    protectionList.push({
      seq:proVal,
      guaranteeProject:'',
      guaranteeAmount:'',
    });
    console.log('后：' + protectionList);
    this.setState({
      comInsGuaProject: protectionList,
      proLength:proVal,
    });
  };

  //减少保障项目
  reduceArea = (seq) => {
    const protectionList = this.state.comInsGuaProject;
    const proVal = this.state.comInsGuaProject.length - 1;
    if (protectionList.length === 1) {
      message.error('至少需要一个保障项目');
      return;
    }
    protectionList.splice(seq,1);
    this.setState({
      comInsGuaProject: protectionList,
      proLength: proVal,
    });
  };

  //时间选择
  handlePanelChange = (value, mode) => {
    this.setState({
      mode: [
        mode[0] === 'date' ? 'month' : mode[0],
        mode[1] === 'date' ? 'month' : mode[1],
      ],
    });
    console.log('mode',mode);
    console.log('value',value);
    const { form } = this.props;
    form.setFieldsValue({rangeTimePicker:value});
  };

  //保障项目
  renderGuaProjectOptions = () =>{
    return this.state.guaProjectOptions.map((val, key) => {
      return <Option key={key} value={val.guaProjectId + ""}>{val.guaProjectName}</Option>;
    });
  };

  selectChange = (index, value) =>{
    const {setFieldsValue} = this.props.form;
    const {comInsGuaProject} = this.state;
    const newList = comInsGuaProject;
    newList[index].guaranteeProject = value; //把对应的保障数据替换某个值，在
    console.log(">>>>>>>>>>",index,value,newList);
    // this.setState({comInsGuaProject:newList}, () => {
    //   console.log(name + index);
    //   setFieldsValue({[`guaranteeProject${index}`]: value});
    // });
  };

  // 添加保障项目
  addProtection = () => {
    // const protectionList = this.state.protectionList;
    const {getFieldDecorator, getFieldValue} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    if(this.state.comInsGuaProject.length === 0){
      this.state.comInsGuaProject = [
        {
          seq:1,
          guaranteeProject:'',
          guaranteeAmount:'',
        }
      ];
    }

    const arr = this.state.comInsGuaProject.map((val, key) => {
      let text = "元";
      if (val.guaranteeProject !== "") {
        const node = this.state.guaProjectOptions.find(val1 => val1.guaProjectId.toString() === val.guaranteeProject);
        if(node){
          text = node.unit;
        }
      }
      // console.log("每个val:",val,this.state.guaProjectOptions);
      const rs =
        (<div key={key}>
            <FormItem {...formItemLayout} label="保障项目" >
              {getFieldDecorator('guaranteeProject' + (key + 1), {
                initialValue: val.guaranteeProject,
                rules: [{required: true, message: '请选择保障项目'}],
              })(
                <Select addonBefore={key + 1} placeholder="请选择保障项目" onChange={this.selectChange.bind(this, key)} >
                  {this.renderGuaProjectOptions()}
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" "
              colon={false}
              className="detailedAddress"
            >
              <div style={{display: 'flex'}}>
                <div style={{flex: 1}}>
                  {getFieldDecorator('guaranteeAmount' + (key + 1), {
                    initialValue: val.guaranteeAmount,
                    rules: [{
                      required: true, message: ('请输入保障项目' + (key + 1) + '金额!'),
                    },{
                      validator: this.checkJinE,
                    }],
                  })(
                    <Input addonAfter={text} placeholder="请输入保障项目金额" style={{width: '50%'}} maxLength="8"/>
                  )}
                </div>
                <div>
                  <Icon type="plus-circle-o" onClick={this.addArea} style={{ marginRight:'24px', marginLeft:'24px'}}/>
                  <Icon type="minus-circle-o" onClick={this.reduceArea.bind(this,key)}/>
                </div>
              </div>
            </FormItem>
          </div>
        );
      // console.log(rs, 'rs');
      return rs;
    });
    // console.log(arr, 'arr');
    return arr;
  };

  callbackReturn = () => {
    const that = this;
    confirm({
      title: '是否放弃本次修改？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        console.log("ok");
        that.props.close();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  render() {
    const {getFieldDecorator, getFieldValue} = this.props.form;
    const {submitting} = this.props;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    const props = {
      action: ajax.uploadUrl,
      name: "xfile",
      onChange: (info) => {
        console.log('>>>>>>>>>>>>>>>>',info.file,this.state.fileList);
        const status = info.file.status;
        const types = ["image/png", "image/jpeg", "image/jpg"];
        // console.log(file.type);
        let ifFormat = false;
        //判断是否图片
        if (info.file.size / 1024 / 1024 >= 3) {
          message.error('文件必须小于3MB!');
          return false;
        }
        if (types.indexOf(info.file.type) !== -1) {
          ifFormat = true;
        }
        if (info.file.name.indexOf(".doc") !== -1) {
          ifFormat = true;
        }
        if (info.file.name.indexOf(".pdf") !== -1) {
          ifFormat = true;
        }
        if (info.file.name.indexOf(".docx") !== -1) {
          ifFormat = true;
        }
        if (info.file.name.indexOf(".doc") !== -1) {
          ifFormat = true;
        }
        if (!ifFormat) {
          message.error("支持扩展名: .doc\\.docx\\.pdf\\.jpg\\.png");
          return;
        }

        const files = info.fileList.filter(val => /(\.doc)|(\.pdf)|(\.docx)|(\.png)|(\.jpg)$/g.test(val.name));
        const fileList = bcx_utils.removeDuplicateObj(files, "name", (name) => {
          message.error(`${name}文件重复`, 1.5);
        });
        console.log(fileList);
        this.setState({fileList});

        if (status === 'error') {
          message.error(`${this.state.fileList[0].name} 文件上传失败。`);
          fileList.splice(fileList.length - 1,1);
          this.setState({ fileList});
        }
        if (status === 'done') {
          message.success(`${this.state.fileList[0].name} 文件上传成功。`);
        }

      },
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        // const types = ["image/png", "image/jpeg", "image/jpg"];
        // // console.log(file.type);
        // let ifFormat = false;
        //判断是否图片
        // if (file.size / 1024 / 1024 >= 3) {
        //   message.error('文件必须小于3MB!');
        //   return false;
        // }
        // if (types.indexOf(file.type) !== -1) {
        //   ifFormat = true;
        // }
        // if (file.name.indexOf(".doc") !== -1) {
        //   ifFormat = true;
        // }
        // if (file.name.indexOf(".pdf") !== -1) {
        //   ifFormat = true;
        // }
        // if (file.name.indexOf(".docx") !== -1) {
        //   ifFormat = true;
        // }
        // if (file.name.indexOf(".doc") !== -1) {
        //   ifFormat = true;
        // }
        // if (!ifFormat) {
        //   message.error("支持扩展名: .doc\\.docx\\.pdf\\.jpg\\.png");
        // }else{
        //   console.log('adfasdfasfasfa');
        // }

        return true;
      },
      fileList: this.state.fileList,
    };

    return (
      <Form onSubmit={this.handleSubmit} style={{marginTop: 24}} className="Insurance_content " >
        <div style={{padding: "24px 24px 0 24px"}} >
          <p style={{
            paddingBottom:"8px",
            fontSize: "16px",
            color: "#333333",
            letterSpacing: "0",
            lineHeight: "16px",
            borderBottom: "1px solid #e9e9e9", }}>保单内容</p></div>
        {this.state.comInsId === '00' ?
        <FormItem {...formItemLayout} label="公司名称" >
          {getFieldDecorator('comName', {
            initialValue: this.state.listPage.comName,
            rules: [{
              required: true, message: '请输入公司名称！',
            }],
          })(
            <Input placeholder="请输入" disabled/>
          )}
        </FormItem> :
        <FormItem {...formItemLayout} label="公司名称" >
          {getFieldDecorator('comName', {
            initialValue: this.state.listPage.comName,
            rules: [{
              required: true, message: '请输入公司名称！',
            }],
          })(
            <Input disabled placeholder="请输入"/>
          )}
        </FormItem>}
        <FormItem {...formItemLayout} label="保险产品名称" >
          {getFieldDecorator('productName', {
            initialValue: this.state.listPage.productName,
            rules: [{
              pattern: /^[\u4e00-\u9fa5]{1,20}$/, message: '请输汉字最大20位!',
            },{
              required: true, message: '请输入保险产品名称！',
            }],
          })(
            <Input placeholder="请输入"/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="在保人数" >
          {getFieldDecorator('perNum', {
            initialValue: this.state.listPage.perNum,
            rules: [{
              pattern: /^[0-9]{1,8}$/, message: '请输数字最大8位!',
            },{
              required: true, message: '请输入在保人数！',
            }],
          })(
            <Input placeholder="请输入"/>
          )}
        </FormItem>
        {this.state.comInsId === '00' ?
        <FormItem {...formItemLayout} label="保险有效期">
          {getFieldDecorator('rangeTimePicker', {
            rules: [{
              type: 'array', required: true, message: '保险有效期不能为空!'
            }],
          })(
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
              mode={this.state.mode}
              onPanelChange={this.handlePanelChange}
              style={{width:'100%'}}
            />
          )}
        </FormItem> :
        <FormItem {...formItemLayout} label="保险有效期" >
          {getFieldDecorator('rangeTimePicker', {
            initialValue:[moment(this.state.listPage.effectStartDate,'YYYY-MM-DD'), moment(this.state.listPage.effectEndDate,'YYYY-MM-DD')],
            rules: [{
              type: 'array', required: true, message: '保险有效期不能为空!'
            }],
          })(
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
              mode={this.state.mode}
              onPanelChange={this.handlePanelChange}
              style={{width:'100%'}}
            />
          )}
        </FormItem>}
        <FormItem {...formItemLayout} label="保险公司名称" >
          {getFieldDecorator('insComName', {
            initialValue: this.state.listPage.insComName,
            rules: [{
              pattern: /^[\u4e00-\u9fa5\（\）]{1,50}$/, message: '请输汉字最大20位!',
            },{
              required: true, message: '请输入保险公司名称！',
            }],
          })(
            <Input placeholder="请输入"/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="保单号" >
          {getFieldDecorator('policyNo', {
            initialValue: this.state.listPage.policyNo,
            rules: [{
              pattern: /^[0-9A-Za-z]{2,30}$/, message: '请输数字或字母最大20长度',
            },{
              required: true, message: '请输入保单号！',
            }],
          })(
            <Input placeholder="请输入"/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="上传保单" extra="支持扩展名: .doc\.docx\.pdf\.jpg\.png" >
          {getFieldDecorator('policyUrl', {
            initialValue: this.state.fileList,
            rules: [
              {required: true, message: '请上传保单'},
            ],
          })(
            <Upload {...props}>
              <Button>
                <Icon type="upload"/> 上传文件
              </Button>
            </Upload>
          )}
        </FormItem>
        <div style={{ padding: "24px 24px 0 24px" }} >
          <p style={{
            paddingBottom:"8px",
            fontSize: "16px",
            color: "#333333",
            letterSpacing: "0",
            lineHeight: "16px",
            borderBottom: "1px solid #e9e9e9", }}>保障信息</p></div>
        <div className="protection">
          {this.addProtection()}
        </div>
        <FormItem {...submitFormLayout} style={{marginTop: 32}}>
          <Button onClick={this.callbackReturn}>返回</Button>
          <Button type="primary" style={{marginLeft: 8}} loading={this.state.loading} htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}
